package com.edais.service.imp;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.edais.dao.KeycodeSendRecordDao;
import com.edais.dao.UserDao;
import com.edais.domain.GetKeyCodeRecode;
import com.edais.domain.User;
import com.edais.domain.UserActivityKeyCode;
import com.edais.service.KcodeService;
import com.edais.util.CommonUtil;
import com.edais.util.IsObjNullUtil;
import com.edais.vo.ChannelConstans;
import com.edais.vo.ResultMsgVo;

@Service
public class KcodeServiceImpl implements KcodeService {

	private static final Log logger = LogFactory.getLog(KcodeServiceImpl.class);

	@Autowired
	private UserDao usersDao;
	@Autowired
	private KeycodeSendRecordDao keycodeSendRecordDao;

	@Override
	public String sendKcode(String logInfo, String merchant, String phone,
			String orderId, String cardNo) throws Exception {
		logger.info(logInfo + "发送K码系统开始");
		String message = "";
		String result = null;

		String ipPort = this.getSendKcodeIpPort();

		String url = "/kms/distributePaperKCode?userId=lbjr&userName=lbjr&phone="
				+ phone + "&systemAp=" + 102 + "&cardNo=";
		StringBuffer urlStr = new StringBuffer(ipPort);
		urlStr.append(url);
		urlStr.append(cardNo);
		logger.info(logInfo + "发送K码系统url" + urlStr.toString());

		try {
			String str=	CommonUtil.doGet(urlStr.toString(), null);
			JSONObject jsonObj = JSONObject.fromObject(str);
			
			logger.info(logInfo + "发送K码系统结果" + jsonObj.toString());
			result = jsonObj.getString("result");// 返回码
			message = jsonObj.getString("message");// 返回信息

		} catch (Exception e) {
			logger.error(logInfo + "调用K码系统异常" + orderId, e);
			message = "调用K码系统异常" + e.toString();
		}

		// 3.更新发送记录表
		Map<String, Object> param = new HashMap<String, Object>();

		if ("0".equals(result)) {
			param.put("status", 1);
			logger.info(logInfo + "调用K码系统成功");
		}
		param.put("message", message);// 发送K码返回信息
		param.put("orderId", orderId);
		param.put("merchant", merchant);
		param.put("cardNo", cardNo);

		int updateResult = keycodeSendRecordDao.updateKCodeSendStatus(param);

		logger.error(logInfo + "调用K码系统后，更新K码发送记录表结果：" + updateResult);

		if (!"0".equals(result)) {
			return ResultMsgVo.RESCODE_3000; // 短信发送失败,cardNo更新成功
		}

		return ResultMsgVo.RESCODE_0000;

	}

	@Override
	public Map<String, Object> updateStatus(String merchant, String userId,
			String phone, String orderId, String money) throws Exception {
		/** 1.查询t_user_activity_keycode_list，获得10个未分配的 cardno **/
		// 保障渠道名字是渲云，库中配的是渲云
		// String channel="xuanyun".equals(merchant)?"渲云":merchant;
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<UserActivityKeyCode> KeyCodeList = keycodeSendRecordDao
				.getKeyCodeListByParm(ChannelConstans.XY_CHANNEL_ID);
		logger.info("拿出carsNo的数量" + KeyCodeList.size());
		if (KeyCodeList != null && KeyCodeList.size() == 0) {
			resultMap.put("rescode", ResultMsgVo.RESCODE_2003);
			resultMap.put("cardNo", "");
			return resultMap;
		}

		String cardNo = null;
		int result = 0;

		for (UserActivityKeyCode userActivityKeyCode : KeyCodeList) {
			cardNo = userActivityKeyCode.getCardNo();
			// 1.先更新T_USER_ACTIVITY_KEYCODE_LIST的状态为1 代表k码已分配 0代表未分配
			logger.info("开始尝试更新cardNo的状态，cardNo=" + cardNo);
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("cardNo", cardNo);
			param.put("status", 1);
			result = keycodeSendRecordDao.updateActivityKeyCodeByCardNo(param);
			if (result != 1) {
				continue;
			}
			logger.info("更新成功cardNo=" + cardNo);

			GetKeyCodeRecode getKeyCodeRecode = new GetKeyCodeRecode();
			getKeyCodeRecode.setUserid(userId);
			getKeyCodeRecode.setCardno(cardNo);
			getKeyCodeRecode.setMobile(phone);
			getKeyCodeRecode.setMoney(new BigDecimal(money));
			getKeyCodeRecode.setOrderid(orderId);
			getKeyCodeRecode.setMerchant(merchant);
			getKeyCodeRecode.setStatus("0");
			logger.info("开始插入K码发送记录信息=" + getKeyCodeRecode.toString());
			keycodeSendRecordDao.insertSelective(getKeyCodeRecode);
			break;
		}
		if (result != 1) {// 系统繁忙请稍后再试
			logger.info("获取cardNo失败orderId=" + orderId);
			resultMap.put("rescode", ResultMsgVo.RESCODE_2002);
			resultMap.put("cardNo", "");
			return resultMap;
		}
		resultMap.put("rescode", ResultMsgVo.RESCODE_0000);
		resultMap.put("cardNo", cardNo);
		return resultMap;
	}

	@Override
	public String checkKcode(String mobile, String userId, String merchant) throws Exception {

		/** 1.(一个用户只能激活一次)根据用户id判断用户不在t_keycode_send_record表中 **/
			String logInfo="接口校验发送资userId和mobile"+"userId="+userId+"mobile="+mobile;
			GetKeyCodeRecode getKeyCodeRecode = keycodeSendRecordDao
					.getKeyCodeRecodeByUserId(userId);
			
			if (IsObjNullUtil.isNotEmpty(getKeyCodeRecode)) {
				logger.info(logInfo+"发送记录"+getKeyCodeRecode.toString());
				logger.info(logInfo+"校验失败订单存在"+getKeyCodeRecode.toString());
				return ResultMsgVo.RESCODE_2004;
		}
			
			Map<String, Object> queryMap = new HashMap<String, Object>();
			queryMap.put("mobile", mobile);
			List<GetKeyCodeRecode> keyCodeRecodeList = keycodeSendRecordDao
					.getKeyCodeRecodeByParm(queryMap);
			
			if (keyCodeRecodeList.size() > 0) {
				logger.info(logInfo+"校验失败用户userId"+userId+"不存在，手机号存在"+keyCodeRecodeList.get(0).toString());
				return ResultMsgVo.RESCODE_1002;
			}
			
			

		/** 2.根据手机号判断用户不在t_user表中 **/
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("mobile", mobile);
		User user = this.usersDao.getUserByParm(map);

		if (IsObjNullUtil.isNotEmpty(user)) {
			logger.info(logInfo+"校验失败用户存在存在");
			return ResultMsgVo.RESCODE_2000;
		}
		logger.info(logInfo+"校验成功");
		return ResultMsgVo.RESCODE_0000;
	}
	
	
	@Override
	public String sendCheckKcode(String mobile, String userId, String merchant,
			String orderId) throws Exception {

			String logInfo="接口校验发送资userId和mobile"+"orderId="+orderId+"mobile="+mobile;

			Map<String, Object> queryMap = new HashMap<String, Object>();
			queryMap.put("orderid", orderId);
			queryMap.put("merchant", merchant);
			List<GetKeyCodeRecode> keyCodeRecodeList = keycodeSendRecordDao
					.getKeyCodeRecodeByParm(queryMap);
			if (keyCodeRecodeList.size() > 0) {
				logger.info(logInfo+"校验失败订单存在"+keyCodeRecodeList.get(0).toString());
				return ResultMsgVo.RESCODE_2004;
			}
			
			
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("mobile", mobile);
			List<GetKeyCodeRecode> codeRecodeList = keycodeSendRecordDao
					.getKeyCodeRecodeByParm(map);
			
			if (codeRecodeList.size() > 0) {
				logger.info(logInfo+"校验失败订单不存在orderId"+orderId+"不存在，手机号存在"+codeRecodeList.get(0).toString());
				return ResultMsgVo.RESCODE_1002;
			}
			


		/** 2.根据手机号判断用户不在t_user表中 **/
		Map<String, Object> parmMap = new HashMap<String, Object>();
		parmMap.put("mobile", mobile);
		User user = this.usersDao.getUserByParm(parmMap);

		if (IsObjNullUtil.isNotEmpty(user)) {
			logger.info(logInfo+"校验失败用户存在存在");
			return ResultMsgVo.RESCODE_2000;
		}
		logger.info(logInfo+"校验成功");
		return ResultMsgVo.RESCODE_0000;
	}

	@Override
	public Map<String, Object> queryResult(String merchant, String orderId)
			throws Exception {
		Map<String, Object> queryMap = new HashMap<String, Object>();
		String logInfo="查询发送结果orderId——"+orderId;
		queryMap.put("orderid", orderId);
		queryMap.put("merchant", merchant);
		logger.info(logInfo+"参数merchant——"+merchant);
		List<GetKeyCodeRecode> keyCodeRecodeList = keycodeSendRecordDao
				.getKeyCodeRecodeByParm(queryMap);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (keyCodeRecodeList.size() == 1) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			GetKeyCodeRecode keyCodeRecode = keyCodeRecodeList.get(0);
			logger.info(logInfo+"查到到发送信息"+keyCodeRecode.toString());
			if(!"1".equals(keyCodeRecode.getStatus())){
				logger.info(logInfo+"调用K码系统短信发送失败"+keyCodeRecode.toString());
				throw new Exception("系统异常");
			}
			resultMap.put("orderId", keyCodeRecode.getOrderid());
			resultMap.put("userId", keyCodeRecode.getUserid());
			resultMap.put("mobile", keyCodeRecode.getMobile());
			resultMap.put("money", keyCodeRecode.getMoney());
			resultMap.put("cardNo", keyCodeRecode.getCardno());
			resultMap.put("createTime",
					sdf.format(keyCodeRecode.getCreatetime()));

		} else if (keyCodeRecodeList.size() == 0) {
			logger.info(logInfo+"没查到数据");
			resultMap.put("orderId", "");
			resultMap.put("userId", "");
			resultMap.put("mobile", "");
			resultMap.put("money", "");
			resultMap.put("cardNo", "");
			resultMap.put("createTime", "");
		}
		logger.info(logInfo+"返回的数据" +resultMap.toString());
		return resultMap;
	}

	@Override
	public String getSecretKey(Integer id) throws Exception {

		// 检查参数

		if (IsObjNullUtil.isEmpty(id)) {
			logger.error("参数id" + id);
			throw new Exception("参数异常 null");
		}
		HashMap<String, Object> resultMap = keycodeSendRecordDao
				.getSecretKey(id);

		if (IsObjNullUtil.isEmpty(resultMap)) {
			logger.error("渠道Id=" + id + "的渠道数据异常");
			throw new Exception("数据异常");
		}

		String key = (String) resultMap.get("SECREKEY");

		if (StringUtils.isBlank(key)) {
			logger.error("渠道Id=" + id + "的渠道数据异常");
			throw new Exception("数据异常");
		}
		return key;
	}
	
	
	
	@Override
	public String resendMsg(String logInfo,String merchant, String phone, String orderId)
			throws Exception {
		logger.info(logInfo + "重新发送K码系统开始");
		
		String message = "";
		String result = null;
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("orderid", orderId);
		map.put("merchant", merchant);
		List<GetKeyCodeRecode> codeRecodeList = keycodeSendRecordDao
				.getKeyCodeRecodeByParm(map);
		
		if (codeRecodeList.size()==0) {
			logger.info(logInfo+"根据订单ID校验没有发送失败的记录"+orderId+"不存在");
			return ResultMsgVo.RESCODE_2006;
		}
		
		
		String cardNo=codeRecodeList.get(0).getCardno();
		String status=codeRecodeList.get(0).getStatus();
		
		if(StringUtils.isBlank(cardNo)){
			logger.info(logInfo+"cardNo"+cardNo+"不存在，手机号存在"+codeRecodeList.get(0).toString());
			return ResultMsgVo.RESCODE_1002;
			
		}
		if(StringUtils.isBlank(status)){
			logger.info(logInfo+"status"+status+"不存在，手机号存在"+codeRecodeList.get(0).toString());
			return ResultMsgVo.RESCODE_1002;
			
		}
		if(!"0".equals(status)){
			logger.info(logInfo+"根据订单ID校验没有发送失败的记录"+orderId+"不存在");
			return ResultMsgVo.RESCODE_2006;
		}
		
		Map<String, Object> queryMap = new HashMap<String, Object>();
		queryMap.put("mobile", phone);
		queryMap.put("status", 1);
		List<GetKeyCodeRecode> keyCodeRecodeList = keycodeSendRecordDao
				.getKeyCodeRecodeByParm(queryMap);
		
		if(keyCodeRecodeList.size()>0){
			logger.info(logInfo+"手机号存在发送成功的记录"+codeRecodeList.get(0).toString());
			return ResultMsgVo.RESCODE_1002;
		}
		
		

		String ipPort = this.getSendKcodeIpPort();

		String url = "/kms/distributePaperKCode?userId=lbjr&userName=lbjr&phone="
				+ phone + "&systemAp=" + 102 + "&cardNo=";
		StringBuffer urlStr = new StringBuffer(ipPort);
		urlStr.append(url);
		urlStr.append(cardNo);
		logger.info(logInfo + "发送K码系统url" + urlStr.toString());

		try {
			
			String str=	CommonUtil.doGet(urlStr.toString(), null);
			JSONObject jsonObj = JSONObject.fromObject(str);
			
			logger.info(logInfo + "发送K码系统结果" + jsonObj.toString());
			result = jsonObj.getString("result");// 返回码
			message = jsonObj.getString("message");// 返回信息

		} catch (Exception e) {
			logger.error(logInfo + "调用K码系统异常" + orderId, e);
			message = "调用K码系统异常" + e.toString();
		}

		// 3.更新发送记录表
		Map<String, Object> param = new HashMap<String, Object>();

		if ("0".equals(result)) {
			param.put("status", 1);
			logger.info(logInfo + "调用K码系统成功");
		}
		param.put("message", message);// 发送K码返回信息
		param.put("orderId", orderId);
		param.put("merchant", merchant);
		param.put("cardNo", cardNo);

		int updateResult = keycodeSendRecordDao.updateKCodeSendStatus(param);

		logger.error(logInfo + "重新调用K码发送系统后，更新K码发送记录表结果：" + updateResult);

		if (!"0".equals(result)) {
			return ResultMsgVo.RESCODE_3000; // 短信发送失败,cardNo更新成功
		}

		return ResultMsgVo.RESCODE_0000;

	}
	
	


	/**
	 * 
	 * @Description: 获得发送K码短信的Url 域名（ip+端口）
	 * @return
	 * @throws Exception
	 * @return String
	 * @author ruXinChao
	 * @date 2016-9-21 上午10:59:58
	 */
	private String getSendKcodeIpPort() throws Exception {
		HashMap<String, Object> map = keycodeSendRecordDao
				.getSendMsgKcodeUrl(ChannelConstans.SEND_KCODE_IP_PORT);

		if (IsObjNullUtil.isEmpty(map)) {
			logger.error("发送K码短信的Url未配置");
			throw new Exception("数据异常");
		}
		String ipPort = (String) map.get("ADDRESS");

		if (StringUtils.isBlank(ipPort)) {
			logger.error("发送K码短信的Url未配置");
			throw new Exception("数据异常");
		}

		return ipPort;

	}

	@Override
	public Map<String, Object> queryResultByPhone(String merchant, String phone)
			throws Exception {
		Map<String, Object> queryMap = new HashMap<String, Object>();
		String logInfo="查询发送结果phone——"+phone;
		queryMap.put("mobile", phone);
		queryMap.put("merchant", merchant);
		logger.info(logInfo+"参数merchant——"+merchant);
		List<GetKeyCodeRecode> keyCodeRecodeList = keycodeSendRecordDao
				.getKeyCodeRecodeByParm(queryMap);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (keyCodeRecodeList.size() == 1) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			GetKeyCodeRecode keyCodeRecode = keyCodeRecodeList.get(0);
			logger.info(logInfo+"查到到发送信息"+keyCodeRecode.toString());
			if(!"1".equals(keyCodeRecode.getStatus())){
				logger.info(logInfo+"调用K码系统短信发送失败"+keyCodeRecode.toString());
				throw new Exception("系统异常");
			}
			resultMap.put("orderId", keyCodeRecode.getOrderid());
			resultMap.put("userId", keyCodeRecode.getUserid());
			resultMap.put("mobile", keyCodeRecode.getMobile());
			resultMap.put("money", keyCodeRecode.getMoney());
			resultMap.put("cardNo", keyCodeRecode.getCardno());
			resultMap.put("createTime",
					sdf.format(keyCodeRecode.getCreatetime()));

		} else if (keyCodeRecodeList.size() == 0) {
			logger.info(logInfo+"没查到数据");
			resultMap.put("orderId", "");
			resultMap.put("userId", "");
			resultMap.put("mobile", "");
			resultMap.put("money", "");
			resultMap.put("cardNo", "");
			resultMap.put("createTime", "");
		}
		logger.info(logInfo+"返回的数据" +resultMap.toString());
		return resultMap;
	}
	
}
